The index( ) Function is used to find the starting position of the substring.
x = "Hello Beautiful World" y = x.index("Beautiful") print("The substring is located at the position ",y)
In the above code, we have declared a String 'Hello Beautiful World' and assigned it to a variable 'x'.
And we would be searching the substring 'Beautiful', from the String, 'Hello Beautiful World'.
So, we have used the 'index( )' Function to find the substring 'Beautiful'.
And what 'index( )' Function does is, goes to the String 'Hello Beautiful World' and searches for the position of the substring 'Beautiful'.
And finds the substring 'Beautiful' in the 6th position. And the position (i.e. '6') is stored in variable 'y'.
And thus prints the position.
Now, let us say you have the below String,
And you have to search for the second occurrence of 'Beautiful'.
To solve this, you can add a second and a third parameter used by 'index( )' function that tells the range, and in between the range the substring can be checked.
Let us see with the below example.
x = "The Beautiful world is Beautiful indeed" y = x.index("Beautiful", 20, 35) print("The substring is located at the position ",y)
So, if you see the above output, only the second occurrence of 'Beautiful' is searched for.
That is because of the below line,
Where we have specified the the range as '20' and '35', in second and third parameter.
Which says that search for the substring 'Beautiful' in the positions between '20' to '35'.
And thus we got the position as '23' assigned to the variable 'y',